import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/group_api.dart';
import 'package:sainbainu/common/models/request/pager_request.dart';
import 'package:sainbainu/common/models/response/group_list_response.dart';
import 'package:sainbainu/common/repositories/group_repository.dart';
import 'package:sainbainu/common/services/publish.dart';

import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/widgets/image_uploader.dart';
import 'package:sainbainu/common/widgets/recorder.dart';
import 'package:sainbainu/view/content_create/state.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'index.dart';

class ContentCreateController extends GetxController {
  ContentCreateController();

  final state = ContentCreateState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    /// 内容聚焦
    state.contentFocusNode = FocusNode();

    /// 链接聚焦
    state.linkFocusNode = FocusNode();

    /// 文本控制器
    state.contentEditingController = TextEditingController()
      ..addListener(() {
        state.text = state.contentEditingController.text;
        update(['submitBtn']);
      });

    /// 链接控制器
    state.linkEditingController = TextEditingController()
      ..addListener(() {
        state.link = state.linkEditingController.text;

        bool linkIsEmpty = true;
        if (state.link == null || state.link!.isEmpty) {
          linkIsEmpty = true;
        } else {
          linkIsEmpty = false;
        }
        if (linkIsEmpty != state.linkIsEmpty.value) {
          state.linkIsEmpty.value = linkIsEmpty;
          update(['submitBtn']);
        }
      });

    state.groupRefreshController = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    state.groupRepository = GroupRepository(GroupApi());
    state.groupPagerRequest = PagerRequest();

    state.imageUploaderController = ImageUploaderController();
    state.customRecorderController = CustomRecorderController();

    getGroupList();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    state.contentFocusNode.dispose();
    state.linkFocusNode.dispose();
    state.contentEditingController.dispose();
    state.linkEditingController.dispose();
    state.groupRefreshController.dispose();
    super.onClose();
  }

  /// 选择视频
  void handleChooseVideo() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.video,
        filterOptions: FilterOptionGroup(
          videoOption: const FilterOption(
            durationConstraint: DurationConstraint(
              max: Duration(minutes: 30),
            ),
            sizeConstraint: SizeConstraint(
              maxWidth: 3840,
              maxHeight: 3840,
            ),
          ),
        ),
      ),
    );
    if (result != null) {
      // 过滤视频大小
      var newVideos = await Util.filterAssetsEntiteis(
        result,
        maxSize: 200,
        onError: (msg) => LoadingUtil.showInfo(msg),
      );
      state.video = newVideos[0];
      update(['asset_video', 'submitBtn']);
    }
  }

  /// 视频删除
  void handleRemoveVideo() {
    state.video = null;
    update(['asset_video', 'submitBtn']);
  }

  /// 监听评论图片选择或清空
  void handleImageChange(List<AssetEntity> images) {
    state.images = images;
    update(['submitBtn']);
  }

  /// 监听录音文件或清空
  void handleAudioChange(String? path, Duration? duration) {
    state.audio = path;
    state.audioDuration = duration;
    update(['submitBtn']);
  }

  /// 获取下组列表
  Future getGroupList({bool refresh = true}) async {
    if (refresh) {
      state.groupPagerRequest.pageNum = 1;
    }
    var res = await state.groupRepository.myList(
      state.groupPagerRequest,
    );
    if (refresh) {
      state.groupListResponse.rows = res.rows;
    } else {
      state.groupListResponse.rows.addAll(res.rows);
    }

    state.groupListResponse.total = res.total;
    state.hasGroupMore =
        state.groupPagerRequest.pageNum * state.groupPagerRequest.pageSize <
            res.total;
    state.groupPagerRequest.pageNum++;
    update(['groupList']);
  }

  /// 小组上拉下载
  Future onGroupRichBottom() async {
    try {
      if (state.hasGroupMore) {
        await getGroupList(refresh: false);
      }
      if (!state.hasGroupMore) {
        state.groupRefreshController.finishLoad(IndicatorResult.noMore);
      } else {
        state.groupRefreshController.finishLoad(IndicatorResult.success);
      }
    } catch (e) {
      state.groupRefreshController.finishLoad(IndicatorResult.fail);
    }
  }

  /// 小组选择
  void handleGroupSelected(CroupItemResponse item) {
    state.groupName.value = item.groupName ?? '';
    state.groupCover = item.cover ?? '';
    state.groupId = item.groupId;
    Get.back();
    update(['submitBtn']);
  }

  /// 清空小组选择
  void clearGroupSelect() {
    state.groupName.value = '';
    state.groupCover = '';
    state.groupId = null;
  }

  /// 小组详情页
  toGroupDetailPage(int? groupId, String? uniqueTag, String? cover) {
    if (groupId == null) return;
    Get.toNamed(
      AppRoutes.groupDetail,
      arguments: {
        'groupId': groupId,
        'uniqueTag': uniqueTag,
        'cover': cover,
      },
    );
  }

  /// 排序
  void handleReorder(int oldIndex, int newIndex) {
    if (newIndex > oldIndex) {
      newIndex = newIndex - 1;
    }
    FormType formType = state.orderableFormTypes.removeAt(oldIndex);
    state.orderableFormTypes.insert(newIndex, formType);
    update(['reorder']);
  }

  /// 清空所有内容
  void resetAll() {
    state.contentEditingController.text = '';
    state.images.clear();
    state.video = null;
    state.audio = null;
    update(['submitBtn', 'asset_video']);

    state.imageUploaderController.clear();
    state.customRecorderController.clear();
  }

  /// 关闭页面
  void onClosePage() {
    Get.until((route) => route.settings.name == AppRoutes.layout);
  }

  /// 发布
  void onPublish() {
    PublishService.to.onPublish(
      text: state.text,
      images: state.images,
      video: state.video,
      audio: state.audio,
      audioDuration: state.audioDuration,
      link: state.link,
      groupId: state.groupId,
      orderableFormTypes: state.orderableFormTypes
          .map((FormType formType) => formType.value)
          .toList(),
    );
    onClosePage();

    /// 等同于上面
    // PublishService publishLogic = Get.find<PublishService>();
    // publishLogic.onPublish(
    //   text: state.text,
    //   images: state.images,
    //   video: state.video,
    //   audio: state.audio,
    // );
  }
}
